﻿using Aspose.Words;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace LdtJudge.DataEngine.Common.CommonWordHandle
{
    /// <summary>
    /// 读取文件的通用操作
    /// </summary>
    public class WordHandle
    {
        public WordHandle()
        {
            string lic = @"<License>
                            <Data>
                            <LicensedTo>Fluor Federal Services</LicensedTo>
                            <EmailTo>t.j.tumlin@fluor.com</EmailTo>
                            <LicenseType>Site Small Business</LicenseType>
                            <LicenseNote>Limited to 10 physical locations, not to exceed 10 developers</LicenseNote>
                            <OrderID>190501090513</OrderID>
                            <UserID>412577</UserID>
                            <OEM>This is not a redistributable license</OEM>
                            <Products>
                            <Product>Aspose.Total for .NET</Product>
                            </Products>
                            <EditionType>Enterprise</EditionType>
                            <SerialNumber>57cbdcb5-e657-4ed1-aed2-b2613bdd3517</SerialNumber>
                            <SubscriptionExpiry>20210106</SubscriptionExpiry>
                            <LicenseVersion>3.0</LicenseVersion>
                            <LicenseInstructions>https://purchase.aspose.com/policies/use-license</LicenseInstructions>
                            </Data>
                            <Signature>GNczbuoKwEEKCQJaQlTugFt30pBwgAEfPAfICZ6v6+CE+ABgm6cblP8I/KMqJiWFAMTf1/jRXR61SqKRFppFl+W1rvnd26YX9fQkI3b/4Vq2JHDr15cZbFNxHmRAAjW6W/bGRcfVBsnIG8XsD7yrp8146G8zbyX2BJ05JTCT2Yc=</Signature>
                            </License>";
            using (MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(lic)))
            {
                //实例化授权
                Aspose.Words.License _license = new Aspose.Words.License();
                //设置授权标识
                _license.SetLicense(memStream);
            }

        }
        /// <summary>
        /// 获取word文件内容
        /// </summary>
        /// <param name="wordPath"></param>
        /// <returns></returns>
        public string GetWordContent(string wordPath)
        {
            Document doc = null;
            using (FileStream fileStream = new FileStream(wordPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                doc = new Document(fileStream, new LoadOptions() { Encoding = Encoding.UTF8 });
            }
            //return GetDocContent(doc);//只获取正文
            return GetDocContentNew(doc);//只获取正文
        }


        /// <summary>
        /// 根据文件流获取文件内容
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <returns></returns>
        public string GerBysetWrodContext(string fileUrl)
        {

            WordHandle wordHandle = new WordHandle();
            WebClient wb = new WebClient();
            byte[] bytes = wb.DownloadData(fileUrl);
            Stream stream = BytesToStream(bytes);
            return GetWordContent(stream);
        }


        public Stream BytesToStream(byte[] bytes)
        {

            Stream stream = new MemoryStream(bytes);

            return stream;

        }
        /// <summary>
        /// 获取全文
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public string GetWordContent(Stream stream)
        {
            Document doc = new Document(stream);
            stream.Close();
            return GetDocContentNew(doc);
        }

        /// <summary>
        /// 获取word文件内容
        /// </summary>
        /// <param name="wordPath"></param>
        /// <returns></returns>
        public string GetWordContent(byte[] filestream)
        {
            Document doc = null;
            using (System.IO.Stream stream = new System.IO.MemoryStream(filestream))
            {
                doc = new Aspose.Words.Document(stream);
                return GetDocContentNew(doc);
            }
        }
        /// <summary>
        /// 获取卷宗的文本内容
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        private string GetDocContentNew(Document doc)
        {
            Dictionary<string, string> replacetext = new Dictionary<string, string>();

            #region 添加需要替换的内容
            replacetext.Add(")", "）");
            replacetext.Add("(", "（");
            replacetext.Add("%o", "‰");
            replacetext.Add("%0", "‰");
            replacetext.Add(";", "；");
            replacetext.Add("?", "？");
            replacetext.Add(":", "：");
            replacetext.Add(",", "，");
            replacetext.Add("''", "“");
            replacetext.Add("<<", "《");
            replacetext.Add(">>", "》");
            replacetext.Add("\t", "");
            replacetext.Add("\\t", "");
            replacetext.Add("\\f", "");
            replacetext.Add("\\0", "");
            replacetext.Add("¶", "");
            replacetext.Add("\\u001e\\u001f", "");
            replacetext.Add("©", "");
            replacetext.Add("®", "");
            replacetext.Add("™", "");
            replacetext.Add("§", "");

            replacetext.Add("\\u0000", "");
            #endregion

            try
            {
                string result = "";
                foreach (var kevalue in replacetext)
                {//进行内容的替换
                    doc.Range.Replace(kevalue.Key, kevalue.Value, new Aspose.Words.Replacing.FindReplaceOptions() { MatchCase = false, FindWholeWordsOnly = false });
                }
                NodeCollection texts = doc.GetChildNodes(NodeType.Body, true);//获取所有body
                foreach (Body item in texts)
                {
                    Dictionary<int, int> dic = new Dictionary<int, int>();
                    foreach (Paragraph p in item.Paragraphs)
                    {
                        if (p.IsListItem)//是列表
                        {
                            int current = p.ListFormat.List.ListId;//列表的编号序号
                            if (!dic.ContainsKey(current))
                            {
                                dic.Add(current, 1);//没有默认从1开始
                            }
                            else
                            {
                                dic[current] = dic[current] + 1;//递增
                            }
                            string t = p.GetText();
                            t = p.ListFormat.List.ListLevels[0].NumberFormat.Replace("\0", dic[current].ToString()) + t;
                            result = result + t;
                        }
                        else
                        {
                            string t = p.GetText().Replace("\f", "\r");
                            result = result + t;
                        }
                    }
                }

                #region 文书内容格式化 -简单格式化处理
                ///2019-03-15 ljx 添加关于文书分析内容中遇到正则关键判定字符导致的错误；

                string formatText = string.Empty;

                using (StringReader sr = new StringReader(result))
                {
                    string line;
                    //.$ ^ { [ ( | ) * + ? \
                    char[] fuhaostart = new char[] { '.', '$', '^', '{', '[', '|', '*', '+', '\\', '-', ',' };
                    char[] fuhaoend = new char[] { '$', '^', '{', '[', '|', '*', '+', '\\', '-', ',' };
                    while ((line = sr.ReadLine()) != null)
                    {
                        line = line.TrimStart(fuhaostart).TrimEnd(fuhaoend);
                        line = line.Replace('?', '？').Replace('(', '（').Replace(')', '）');
                        line = line.Replace("\v", "\r");
                        formatText += line + "\r";
                    }
                }

                result = formatText;
                result = result.Replace("\0", "").Replace("\\u0000","");
                #endregion

                #region 对文本内容进行数字中间有空格格式化处理

                result = System.Text.RegularExpressions.Regex.Replace(result, @"(?<=\d)\s(?=[\d\s]+元)", "");

                #endregion

                return result;

            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 获取文档原文 处理自动编号序号丢失问题
        /// </summary>
        /// <param name="doc">文档</param>
        /// <returns></returns>
        protected string GetDocContent(Document doc)
        {
            Dictionary<string, string> replacetext = new Dictionary<string, string>();

            #region 添加需要替换的内容
            replacetext.Add(")", "）");
            replacetext.Add("(", "（");
            //replacetext.Add("皖日", "皖H");
            replacetext.Add("%o", "‰");
            replacetext.Add("%0", "‰");
            replacetext.Add(";", "；");
            replacetext.Add("?", "？");
            replacetext.Add(":", "：");
            replacetext.Add(",", "，");
            replacetext.Add("''", "“");
            replacetext.Add("<<", "《");
            replacetext.Add(">>", "》");
            replacetext.Add("\t", "");
            //replacetext.Add("H", "日");
            //replacetext.Add("宜读", "宣读");
            //replacetext.Add("曰", "日");
            //replacetext.Add("巳", "已");
            //replacetext.Add("体庭", "休庭");
            //replacetext.Add("入民", "人民");
            //replacetext.Add("途期", "逾期");
            //replacetext.Add("承扣", "承担");
            replacetext.Add("\\t", "");
            replacetext.Add("\\f", "");
            replacetext.Add("¶", "");
            replacetext.Add("…", "");
            replacetext.Add("—", "");
            replacetext.Add("–", "");
            replacetext.Add("\\u001e\\u001f", "");
            replacetext.Add("©", "");
            replacetext.Add("®", "");
            replacetext.Add("™", "");
            replacetext.Add("§", "");


            #endregion

            try
            {
                string result = "";
                foreach (var kevalue in replacetext)
                {//进行内容的替换
                    doc.Range.Replace(kevalue.Key, kevalue.Value, new Aspose.Words.Replacing.FindReplaceOptions() { MatchCase = false, FindWholeWordsOnly = false });
                }

                NodeCollection text = doc.GetChildNodes(NodeType.Paragraph, true);//获取所有段落
                Dictionary<int, int> dic = new Dictionary<int, int>();
                for (int i = 0; i < text.Count; i++)//遍历段落
                {
                    Paragraph p = text[i] as Paragraph;
                    if (p.IsListItem)//是列表
                    {
                        int current = p.ListFormat.List.ListId;//列表的编号序号
                        if (!dic.ContainsKey(current))
                        {
                            dic.Add(current, 1);//没有默认从1开始
                        }
                        else
                        {
                            dic[current] = dic[current] + 1;//递增
                        }
                        string t = p.GetText();
                        t = p.ListFormat.List.ListLevels[0].NumberFormat.Replace("\0", dic[current].ToString()) + t;
                        result = result + t;
                    }
                    else
                    {
                        string t = p.GetText().Replace("\f", "\r");
                        result = result + t;
                    }
                }

                #region 文书内容格式化 -简单格式化处理
                ///2019-03-15 ljx 添加关于文书分析内容中遇到正则关键判定字符导致的错误；

                string formatText = string.Empty;

                using (StringReader sr = new StringReader(result))
                {
                    string line;
                    //.$ ^ { [ ( | ) * + ? \
                    char[] fuhaostart = new char[] { '.', '$', '^', '{', '[', '|', '*', '+', '\\', '-', ',' };
                    char[] fuhaoend = new char[] { '$', '^', '{', '[', '|', '*', '+', '\\', '-', ',' };
                    while ((line = sr.ReadLine()) != null)
                    {
                        line = line.TrimStart(fuhaostart).TrimEnd(fuhaoend);
                        line = line.Replace('?', '？').Replace('(', '（').Replace(')', '）');
                        formatText += line + "\r";
                    }
                }

                result = formatText;

                #endregion

                #region 对文本内容进行数字中间有空格格式化处理

                result = System.Text.RegularExpressions.Regex.Replace(result, @"(?<=\d)\s(?=[\d\s]+元)", "");

                #endregion

                return result;

            }
            catch
            {
                return "";
            }
        }


    }
}
